package com.imaker.frame.utils

import android.content.Context
import android.graphics.Typeface

/**
 * @author ziheng
 * @Description: 替换全局的字体样式
 * 使用：        FontsOverride.setDefaultFont(context, "MONOSPACE", "font/yuanjiao_regular.ttf")
 * @date 2022/12/27 17:21
 */
object FontsOverride {
    fun setDefaultFont(
        context: Context,
        staticTypefaceFieldName: String?, fontAssetName: String?
    ) {
        val regular = Typeface.createFromAsset(
            context.assets,
            fontAssetName
        )
        replaceFont(staticTypefaceFieldName, regular)
    }

    private fun replaceFont(
        staticTypefaceFieldName: String?,
        newTypeface: Typeface?
    ) {
        try {
            val staticField = Typeface::class.java
                .getDeclaredField(staticTypefaceFieldName)
            staticField.isAccessible = true
            staticField[null] = newTypeface
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }
    }
}